package com.haohan.stock.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;

import com.haohan.stock.domain.Stock30;
import com.haohan.stock.vo.SpringDataPageable;

@Component
public class StockDAO {

	@Autowired
	public MongoTemplate mongoTemplate;

	@Autowired
	public GridFsTemplate gridFsTemplate;

	public void save(Stock30 stock) {
		Criteria criteria =Criteria.where("day").is(stock.getDay());
		criteria.andOperator(Criteria.where("code").is(stock.getCode()));
		Query query = Query.query(criteria);
		Update update = Update.update("open",stock.getOpen());
		update.set("high",stock.getHigh());
		update.set("low",stock.getLow());
		update.set("close",stock.getClose());
		update.set("volume",stock.getVolume());
		update.set("price5",stock.getPrice5());
		update.set("price10",stock.getPrice10());
		update.set("price20",stock.getPrice20());
		update.set("price30",stock.getPrice30());
		update.set("volume5",stock.getVolume5());
		update.set("volume10",stock.getVolume10());
		update.set("volume20",stock.getVolume20());
		update.set("volume30",stock.getVolume30());
		update.set("upward_momentum",stock.getUpward_momentum());
		update.set("buy_point",stock.isBuy_point());
		update.set("sell_point",stock.isSell_point());
		mongoTemplate.upsert(query, update, Stock30.class);
	}
	
	public Page<Stock30> select(String code) {
		SpringDataPageable pageable = new SpringDataPageable();
		Criteria criteria = Criteria.where("code").is(code);
		Query query = Query.query(criteria);
	    List<Order> orders = new ArrayList<Order>();  //排序
	    orders.add(new Order(Direction.ASC, "day"));
	    Sort sort = new Sort(orders);
	    // 排序
	    pageable.setSort(sort);
	    // 查询出一共的条数
	    Long count = mongoTemplate.count(query, Stock30.class);
	    // 查询
	    List<Stock30> list = mongoTemplate.find(query.with(pageable), Stock30.class);
	    // 将集合与分页结果封装
	    Page<Stock30> pagelist = new PageImpl<Stock30>(list, pageable, count);
	    return pagelist;
	}

}
